/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    InspectRecordLayout, InternalItemProps, OriginalViewProps, useInputControlSure, useItemInputControl,
} from "../../common/base";
import {assertNamesUnique, createItem, EditorAreaConfig,} from "../../common/eHelper";
import {useRecordListSubX} from "../../hook/useRecordListSub";
import {EditStorageContext} from "../../StorageContext";
import {
    BlobInputList, Button, Input, InputLine, Text, TextArea, useToast
} from "customize-easy-ui-component";
import {useMedia} from "use-media";
import {Each_ZdSetting, useTableEditor} from "../../hook/useRepTableEditor";
import {useMeasureInpFilter} from "../../common/hooks";
import {useUppyUpload} from "../../hook/useUppyUpload";
import {TestMethod} from "../../cm/radio/editor";

export const OriginalView=
    React.forwardRef((
        { action: modAction,  verId, repId='', inp, rep}:OriginalViewProps, ref
    ) => {
      const {storage, setStorage} =React.useContext(EditStorageContext) as any;
      const { _OUT_ROUNDNESS: SubRepIds }=storage;
      if(undefined===SubRepIds)
         return <div>请先确定网络和服务器是正常的。然后才考虑是否要做：
                      <Button intent='danger' onPress={() => setStorage({...storage, _OUT_ROUNDNESS: [] }) }>
                      还没有数据！立刻初始化</Button></div>;
      return <OriginalViewInner ref={ref} action={modAction} verId={verId} repId={repId} rep={rep}/>
} );

/**为了解决useProjectListAs({count: refCount } )因为变动{前面storage数据{有OUT_ROUNDNESS没有THICK_MS}和后面storage{有THICK_MS}数据不一样的}，导致hook报错！
 * 只好拆分成2层次嵌套拼装的俩组件了。父组件可以逻辑return子组件可用hook，不违反hook规则不报错。
 * */
const OriginalViewInner=
    React.forwardRef((
        { action: modAction,  verId, repId='', rep}:OriginalViewProps, ref
    ) => {
        const titleRender = (store: any) => {
            const firstTag=store?.部件;
            return <> { `[${firstTag}] `} </>;
        }
      const {list}=useRecordListSubX(ref,rep,repId,recordPrintList,modAction,verId,'OUT_ROUNDNESS',titleRender);
      return <React.Fragment>
        {list}
      </React.Fragment>;
} );

export const config测量仪 = [
    [['部件名称', '部件'], ['表面状态', '表面'] ],
    [['部件规格', '规格', ], ['仪器名称', '仪器名'] ],
    [['仪器编号', '仪器编'],  ['仪器型号', '仪器型'],  ['仪器精度', {n:'仪器精',u:'mm'}] ],
    [['执行标准',{r:<Text css={{textAlign: 'left',display:'block'}}>DL 647《电力工业锅炉压力容器检验规程》、DL/T515《电站弯管》</Text>}]],
];

const 示图说明选: string[] | undefined=[ ];
const itemA测点位置=['示图说明','_FILE_S部位','检测结果'];

export const ResultDiagram=
    React.forwardRef((
        { children, show ,alone=true,redId,nestMd, repId,label}:InternalItemProps,  ref
    ) => {
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const [getInpFilter] = useMeasureInpFilter(null, itemA测点位置, );
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
            onSure({...inp, '_FILE_S部位': upfile});
            !modified && setModified(true);
        }, [inp, modified,onSure,setModified]);
        const [uploadDom]=useUppyUpload({ repId:repId!,
                  maxFile:5, onFinish, storeObj: inp?._FILE_S部位
        });
        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                                 alone={alone}  label={label!}>
                <InputLine label='检查部位示意图：'>
                    <BlobInputList value={inp?.示图说明 || ''} rows={4} datalist={示图说明选}
                                   onListChange={v => setInp({...inp, 示图说明: v || undefined}) } />
                </InputLine>
                检测部位示意图：
                {uploadDom}
                检测结果:
                <TextArea  value={inp?.检测结果 ||''} rows={3}
                           onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
                {children}
            </InspectRecordLayout>
        );
    } );

export const config测量=[['测点编号','n',100],['实测最大外径(mm)','x',120],['实测最小外径(mm)','i',120] ] as Each_ZdSetting[];
const itemA测量=['测量表', ];
export const EvaluationForm=
    React.forwardRef(({ children, show ,alone=true,refWidth,redId,nestMd,label}:InternalItemProps,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA测量, );
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const headview=<Text variant="h5">
            弯管不圆度测量报告-测点 外径测量。
        </Text>;
        const [render]=useTableEditor({inp, setInp,  headview,
            config: config测量, table: '测量表',  maxRf:4 });

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={label!}>
                {render}
            </InspectRecordLayout>
        );
    } );

/**开发的工具
 * */
const EntranceSetup =
    React.forwardRef((
        {children, show, alone = true, repId, verId, rep}: InternalItemProps, ref
    ) => {
        const atPrint = useMedia('print');
        const toast = useToast();
        const doCheckNames = React.useCallback((verId: string) => {
            const result = assertNamesUnique([{value: rep?.tzFields},
                {value: config测量仪, type:'esnt'},
                {value:[ ...itemA测点位置, ...itemA测量, ]},
            ]);
            toast({title: "完成！", subtitle: result ? "没发现冲突" : "测试开关没开", intent: "success"});
        }, [rep,toast]);
        const {storage, setStorage} =React.useContext(EditStorageContext) as any;
        const getInpFilter = React.useCallback((par: any) => {
            const {_tblFixed, } =par||{};
            return {_tblFixed, };
        }, []);
        const {inp, setInp} = useItemInputControl({ref});
        if (atPrint) return null;
        else return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={'初始化本报告，默认值配置等'}>
                {process.env.REACT_APP_TEST==='true' && <><div>
                    <Text variant="h5">构建开发模板时的工具：校验模板的存储name冲突；</Text>
                    <Button intent='primary' onPress={() => doCheckNames(verId!)}>校验模板name唯一性</Button>
                    <Text variant="h5">设置待测试表格的各列宽度：</Text>
                    <TextArea value={storage?._tblFixed || ''} rows={2} onChange={e =>{
                        JSON.parse(e.currentTarget.value??'[]');
                        setStorage({ ...storage, _tblFixed: e.currentTarget.value || undefined}); }}/>
                </div></>
                }
                <hr/>
            </InspectRecordLayout>
        );
    });

const defvcbFunc = (par: any) => {
    // if(!par.表面)  par.表面='表面清理';
    return  par;
};
//用了TestMethod缺点：没法向Instrument页面去添加一个独立的编辑字段。
const recordPrintList = [
    createItem('Entrance', <EntranceSetup/>),
    createItem('Instrument', <TestMethod config={config测量仪}  defValCb={defvcbFunc} label={'弯管不圆度测量报告-概况'}/>),
    createItem('ResultDiagram', <ResultDiagram label={'弯管不圆度测量-检测部位示意图'}/>),
    createItem('EvaluationForm', <EvaluationForm label={'弯管不圆度测量报告-测量表'}/>),
] as EditorAreaConfig[];
